<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '仅保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
    {
      title: '审核通过',
      icon: '',
      type: 'success',
      hidden: route.query.type !== '4',
      click: (form: any) => {
        proxy.$messageBox('是否审核通过，请确认！', () => {
          setState(form, 2, '审核成功')
        });
      },
    },
    {
      title: '审核拒绝',
      icon: '',
      type: 'danger',
      hidden: route.query.type !== '4',
      click: (form: any) => {
        proxy.$messageInputBox('请填写拒绝原因！', (value: string) => {
          setState(form, 3, '拒绝成功', value)
        });
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createPersonName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
    {
      label: '审核人员',
      value: 'auditorName',
    },
    {
      label: '审核时间',
      value: 'auditTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :data="data.productOrder" :produceTaskBillNo="route.query.produceTaskBillNo" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="退货单号" prop="creditBillNo">
              <ElInputBox :data="form" dataName="creditBillNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="采购单号" prop="purchaseOrderNo" isRules>
              <ElInputBox :data="form" dataName="purchaseOrderNo" disabled />
              <template #btn v-if="isEdit">
                <SelectPurchase @selectBtn="(row: any) => {
                  const _row = row[0]
                  form.purchaseOrderNo = _row.purchaseOrderNo
                  form.supplierCode = _row.supplierCode
                  form.detailList = []
                  getGoods(true)
                }" />
              </template>
            </ElFormItemBox>
            <ElFormItemBox label="供应商" prop="supplierCode" isRules>
              <ElSelectBox :data="form" dataName="supplierCode" :options="options.supplier" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="退货原因" prop="creditBillRemark" class="wAuto" isRules>
              <ElInputBox :data="form" dataName="creditBillRemark" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox :label="`${form.creditState === 3 ? '拒绝' : '作废'}原因`" prop="reason" class="wAuto" isRules
              v-if="[3, 4].includes(form.creditState)">
              <ElInputBox :data="form" dataName="reason" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <GoodList :data="{
            disabled: !isEdit,
            height: 370,
            rowKey: 'specificationCode',
            search: {
              supplierCode: form.supplierCode,
            },
            prop: 'detailList',
            tbody: form.detailList,
            thead: [
              {
                label: '采购数量',
                prop: 'purchaseQuantity',
                formType: 'number',
                disabled: true,
                width: 120,
              },
              {
                label: '已退数量',
                prop: 'creditedQuantity',
                formType: 'number',
                disabled: true,
                width: 120,
              },
              {
                label: '退货数量',
                prop: 'creditQuantity',
                formType: 'number',
                isRules: true,
                width: 120,
                changeBtn: (value: any, row: any) => {
                  //待退货数量
                  const _number = row.purchaseQuantity - row.creditedQuantity
                  if (row.creditQuantity > _number) {
                    proxy.$message('退货数量不能大于采购数量', 'error')
                    row.creditQuantity = _number
                  }
                }
              },
              {
                label: '备注',
                prop: 'creditDetailRemark',
                formType: 'textarea'
              },
            ],
            options: options.goods,
            operation: [
              {
                label: '删除',
                icon: 'Delete',
              }
            ],
            addSelect: {
              title: '采购明细',
              rowKey: 'specificationCode',
              thead: [
                {
                  label: '物料编号',
                  prop: 'specificationCode',
                  align: 'center',
                  width: 120,
                },
                {
                  label: '物料名称',
                  prop: 'goodsName',
                  align: 'left',
                  width: null,
                },
                {
                  label: '规格型号',
                  prop: 'stockGoodsName',
                  align: 'center',
                  width: 120,
                },
                {
                  label: '生产批次',
                  prop: 'productionBatchNumber',
                  align: 'center',
                  width: 120,
                },
                {
                  label: '生产日期',
                  prop: 'productionDate',
                  align: 'center',
                  width: 120,
                },
                {
                  label: '采购数量',
                  prop: 'purchaseQuantity',
                  align: 'center',
                  width: 120,
                },
                {
                  label: '已退数量',
                  prop: 'creditedQuantity',
                  align: 'center',
                  width: 160,
                },
              ],
              tbody: options.goods,
            }
          }" @selectBtn="addMx">
          </GoodList>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
const { dataInfo, options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    creditID: 0, // 退货单主键ID
    creditPeopleCode: "", // 退货人员编码
    supplierCode: "", // 供应商编码
    purchaseOrderNo: "", // 采购单据号
    creditBillRemark: "", // 退货单备注，
    detailList: [
      // {
      //   stockGoodsCode: "", // 库存物品编码
      //   creditQuantity: 10.5, // 退货数量
      //   creditDetailRemark: "", // 退货明细备注
      //   productionBatchCode: "", // 生产批次编码
      //   associationDetailNo: "" // 申请单明细code
      // }
    ]
  },
  associationDetailNo: '',//申请单明细code
});
const isEdit = ref(true)

import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//添加明细
const addMx = (rows: any) => {
  const form = data.form
  let _arr = rows.map((el: any) => ({
    stockGoodsCode: el.stockGoodsCode, // 采购物料编码
    specificationCode: el.specificationCode, // 物料编码
    purchaseQuantity: el.planPurchaseQuantity, // 采购数量
    creditedQuantity: el.creditedQuantity || 0, // 已退数量
    creditQuantity: null, // 退货数量
    creditDetailRemark: "", // 退货明细备注
    productionBatchCode: el.productionBatchCode, // 生产批次编码
    associationDetailNo: el.purchaseDetailCode // 申请单明细code
  }))
  if (!!!form.supplierCode) {
    form.supplierCode = _arr[0].supplierCode
    _arr = _arr.filter((el: any) => el.supplierCode === form.supplierCode)
  }
  form.detailList.push(..._arr)
}
//获取数据
const getForm = async () => {
  let _query: any = route.query
  setLoading()
  //获取工单信息
  //是否新建
  if (!!!_query.code) {
    data.loading = false
    return
  }
  proxy.$api.StockGoodsCredit.GetSingleStockGoodsCredit({
    queryBy: 1,
    queryValue: _query.code,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = (['1', '2'].includes(_query.type) && res.creditState === 0)
      data.form = res
      getGoods()
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const getGoods = (isAdd: boolean = false) => {
  proxy.$api.GoodsPurchaseOrder.GetMatchPagePurchaseOrders({
    pageIndex: 1, //当前页码
    pageSize: 1, //每页显示数据的数量
    totalCount: 0, //总数量
    queryDataBaseFiled: 'purchaseOrderNo', // 关键字查询字段，空值表示查询全部
    likeWords: data.form.purchaseOrderNo, // 查询关键字，空值表示不进行过滤
    beginTime: '', // 查询时间范围起始值（建议格式：yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss）
    endTime: '', // 查询时间范围结束值
    onlySelf: 0, // 是否只查自己创建的数据：0 查所有；1 只查自己
    isShowDisabled: -1, // 是否显示禁用/作废数据：-1 所有；0 未作废；1 仅作废
    orderByFiled: '', // 排序字段名称，如 createTime、updateTime 等
    orderByType: 0, // 排序方式：0 倒序；1 升序
    //差异
    purchaseType: '', // 采购类型（外联字典明细表唯一识别码），空值查询全部
    supplierCode: '', // 供应商编码，空值查询全部
    purchaseOrderState: -2, // 采购单状态：0待确认；1已确认；2已到货；-1已作废，-2查询全部
    inStockState: -2, // 入库状态：0待入库；1已入库；-1已拒绝，-2查询全部
  })
    .then((res: any) => {
      options.goods = res.list[0]?.purchaseDetailsList || [];
      if (isAdd) {
        addMx(options.goods)
      }
    })
    .catch(() => {
    });
}
const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _form: any = {
    creditID: form.creditID, // id
    creditBillNo: form.creditBillNo, // id
    creditPeopleCode: form.creditPeopleCode || proxy.$user.userCode, // 退货人员
    supplierCode: form.supplierCode, // 供应商编码
    purchaseOrderNo: form.purchaseOrderNo, // 退货单据号
    creditBillRemark: form.creditBillRemark, // 备注
    detailList: form.detailList.map((el: any) => (
      {
        stockGoodsCode: el.stockGoodsCode, // 物料编码
        creditQuantity: el.creditQuantity, // 退货数量
        creditDetailRemark: el.creditDetailRemark, // 退货备注
        productionBatchCode: el.productionBatchCode, // 生产批次编码
        associationDetailNo: el.associationDetailNo || data.associationBillNo, // 申请单明细code
      }
    ))
  }
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.StockGoodsCredit.AddStockGoodsCredit({
        ..._form,
      })
        .then((res: any) => {
          if (isConfirm) {
            setState(res, 1, '确认成功')
          } else {
            _sun()
          }

        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.StockGoodsCredit.UpdateStockGoodsCredit(_form)
        .then((res: any) => {
          if (isConfirm) {
            setState(_form, 1, '确认成功')
          } else {
            _sun()
          }
        })
        .catch(() => { });
      break;

    default:
      break;
  }

  function _sun() {
    proxy.$message('保存成功')
    closeBtn()
  }
};

const closeBtn = () => {
  sendMsg('save', true);
  // getForm()
  window.close();
};
//更改状态
const setState = (row: any, state: number = 0, message: string = '操作成功', reason?: string) => {
  proxy.$api.StockGoodsCredit.UpdateStockGoodsCreditState({
    creditBillNo: row.creditBillNo, //核价单号
    reason: reason, //作废/审核拒绝原因
    state: state, //状态：0待确认；1已确认；2已完成；3已拒绝；4已作废
  })
    .then((res: any) => {
      proxy.$message(message);
      closeBtn();
    })
    .catch(() => { });
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};

onMounted(() => {
  getForm();
});
</script>
